package com.newflypig.jblog.controller;

import java.io.File;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.newflypig.jblog.exception.JblogException;
import com.newflypig.jblog.model.BlogCommon;
import com.newflypig.jblog.model.BlogConfig;
import com.newflypig.jblog.model.Result;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;

@Controller
public class UploadController {
	
	@Autowired
	private BlogCommon blogCommon;
	
	@RequestMapping(value="/uploadfile",method=RequestMethod.POST)
	public ModelAndView upload(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "file", required = false) MultipartFile attach){
		String rootPath = request.getSession().getServletContext().getRealPath("/upload/");
		response.setHeader( "Content-Type" , "text/html" );
		ModelAndView mv = new ModelAndView("upload_result");
		try {
			File filePath=new File(rootPath);		
			/**
			 * 文件路径不存在则需要创建文件路径
			 */
			if(!filePath.exists()){
				filePath.mkdirs();
			}
			
			//最终文件名
			String fileExt = attach.getOriginalFilename().substring(attach.getOriginalFilename().lastIndexOf('.'));
	        File realFile=new File(rootPath + File.separator + UUID.randomUUID().toString() + fileExt);
	        FileUtils.copyInputStreamToFile(attach.getInputStream(), realFile);
			
	        mv.addObject("success", 1);
			mv.addObject("message", "上传成功");
			mv.addObject("fileName", blogCommon.getBlogUrl() + "/upload/" + realFile.getName());
		} catch (Exception e) {
			e.printStackTrace();
			mv.addObject("success", 0);
			mv.addObject("message", "上传失败，异常信息：" + e.getMessage());
		}
		
		return mv;
	}
	
	/**
	 * 七牛上传令牌获取
	 * @return
	 * @throws JblogException 
	 */
	@RequestMapping(value="/getQiniuToken",method=RequestMethod.POST)
	public ModelAndView qiniu() throws JblogException{
		Result result = new Result();
		
		if(StringUtils.isEmpty(BlogConfig.QN_ACCESSKEY) || StringUtils.isEmpty(BlogConfig.QN_SECRETKEY)){
			result.setCode(Result.FAIL);
			result.setMessage("数据库中没有正确的七牛服务器密钥，无法生成令牌");
			return new ModelAndView("ajaxResult", "result", result);
		}
		
	    Auth auth = Auth.create(BlogConfig.QN_ACCESSKEY, BlogConfig.QN_SECRETKEY);
		String token = auth.uploadToken(
			"blog-images",	//空间名称
			null,			//key，最终资源名称，一般为空，让服务器自己生成
			3600,			//3600秒，上传时限
			new StringMap()	//其他上传策略
				.put("saveKey", UUID.randomUUID().toString() + "$(ext)")
		);
		
		result.setData("\"" + token + "\"");
		
	    return new ModelAndView("ajaxResult", "result", result);
	}
}
